'use strict';
const axios = require('axios');
const semver = require('semver');
const urlJoin = require('url-join');

async function getNpmInfo(npmName, registry = '') {
  const registryUrl = registry || getDefaultRegistry();
  const url = urlJoin(registryUrl, npmName);
  return axios.get(url).then(res => {
		if (res.status === 200) {
			return res.data;
		}
		return null;
	}).catch(err => {
	  return Promise.reject(err);
	})
}

async function getNpmVersions(npmName, registry = '') {
  const data = await getNpmInfo(npmName, registry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    return [];
  }
}

function getDefaultRegistry(isOriginal = false) {
	return isOriginal ? 'https://registry.npmjs.org' : 'https://registry.npmmirror.com';
}

function getSemverVersions(baseVersion, versions) {
  return versions.filter(version => semver.satisfies(version, `^${baseVersion}`)).sort((a, b) => semver.gt(b, a));
}

async function getNpmSemverVersion(baseVersion, npmName, registry = '') {
  const versions = await getNpmVersions(npmName, registry);
  let newVersions = getSemverVersions(baseVersion, versions)
  if(newVersions && newVersions.length > 0){
		newVersions = sortVersion(newVersions);
		return newVersions.slice(-1)[0];
	}
}

async function getNpmLatestVersion(npmName, registry = '') {
  const versions = await getNpmVersions(npmName, registry);
	if (versions && versions.length > 0) {
		const newVersions = sortVersion(versions);
		return newVersions.slice(-1)[0];
	}
	return null
}

// 版本号数组排序, 从小到大排序
function sortVersion(versionsList) {
  const versions = versionsList.slice()
	return versions.sort((a, b) => {
		let arrA = a.split('.').map(Number);
		let arrB = b.split('.').map(Number);
	
		for (let i = 0; i < Math.max(arrA.length, arrB.length); i++) {
			if ((arrA[i] || 0) < (arrB[i] || 0)) {
				return -1;
			} else if ((arrA[i] || 0) > (arrB[i] || 0)) {
				return 1;
			}
		}
		return 0;
	});
}

module.exports = {
  getNpmInfo,
  getNpmVersions,
  getNpmSemverVersion,
	getDefaultRegistry,
	getNpmLatestVersion
}

